import Vue from 'vue'
import VueRouter from 'vue-router'
// 1级路由
import login from '@/views/login'
import layout from '@/views/layout'
// 2级路由
import home from '@/views/home'
import ask from '@/views/ask'
import mine from '@/views/mine'
import video from '@/views/video'
// 导航守卫
import store from '@/store'
import { Toast } from 'vant'
Vue.use(Toast)
Vue.use(VueRouter)
// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/layout/home' },
    { name: 'login', path: '/login', component: login },
    {
      name: 'layout',
      path: '/layout',
      component: layout,
      children: [
        { name: 'home', path: 'home', component: home },
        { name: 'ask', path: 'ask', component: ask },
        {
          name: 'mine',
          path: 'mine',
          component: mine,
          meta: {
            needLogin: true
          }
        },
        { name: 'video', path: 'video', component: video }
      ]
    }
  ]
})
// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (store.state.user.tokenObj.token) {
      next()
    } else {
      Toast('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    next()
  }
})
export default router
